package org.luxor.commons.mvc.config;

import org.luxor.commons.core.constant.FilterOrdered;
import org.luxor.commons.mvc.config.properties.SignatureProperties;
import org.luxor.commons.mvc.filter.SignatureFilter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.servlet.DispatcherType;

/**
 * API接口签名配置
 *
 * @author Mr.yan  @date 2022/11/3
 */
@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties(SignatureProperties.class)
@ConditionalOnProperty(prefix = SignatureProperties.PREFIX, name = "enabled", havingValue = "true")
public class SignatureConfig {

    @Resource
    private SignatureProperties signatureProperties;

    @Bean
    public FilterRegistrationBean<SignatureFilter> signatureFilterRegistration() {
        SignatureFilter signatureFilter = new SignatureFilter(signatureProperties);
        FilterRegistrationBean<SignatureFilter> registration = new FilterRegistrationBean<>(signatureFilter);
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setOrder(FilterOrdered.SIGNATURE_FILTER_PRECEDENCE.getOrder());
        registration.setName("signatureFilter");
        registration.addUrlPatterns(signatureProperties.includeUrlPatterns());
        registration.addInitParameter("exclusions", signatureProperties.getExcludeUris());
        return registration;
    }
}
